from sqlalchemy import Column, Integer, String, Boolean, DateTime, Text, JSON, ForeignKey, Enum
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from app.core.database import Base
import enum


class TeamRole(str, enum.Enum):
    LEADER = "leader"
    MEMBER = "member"
    PENDING = "pending"


class TeamStatus(str, enum.Enum):
    ACTIVE = "active"
    DISBANDED = "disbanded"
    COMPLETED = "completed"


class Team(Base):
    __tablename__ = "teams"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False)
    description = Column(Text)
    avatar_url = Column(String(500))
    
    # 关联竞赛
    competition_id = Column(Integer, ForeignKey("competitions.id"), nullable=False)
    
    # 团队设置
    is_public = Column(Boolean, default=True)  # 是否公开招募
    max_members = Column(Integer, default=5)
    required_skills = Column(JSON, default=list)  # 需要的技能
    
    # 状态
    status = Column(Enum(TeamStatus), default=TeamStatus.ACTIVE)
    member_count = Column(Integer, default=1)
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关系
    competition = relationship("Competition", back_populates="teams")
    members = relationship("TeamMember", back_populates="team")
    projects = relationship("Project", back_populates="team")
    invitations = relationship("TeamInvitation", back_populates="team")


class TeamMember(Base):
    __tablename__ = "team_members"

    id = Column(Integer, primary_key=True, index=True)
    team_id = Column(Integer, ForeignKey("teams.id"), nullable=False)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    role = Column(Enum(TeamRole), default=TeamRole.MEMBER)
    
    # 加入信息
    joined_at = Column(DateTime(timezone=True), server_default=func.now())
    contribution_note = Column(Text)  # 贡献说明
    
    # 关系
    team = relationship("Team", back_populates="members")
    user = relationship("User", back_populates="teams")


class TeamInvitation(Base):
    __tablename__ = "team_invitations"

    id = Column(Integer, primary_key=True, index=True)
    team_id = Column(Integer, ForeignKey("teams.id"), nullable=False)
    inviter_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    invitee_email = Column(String(255), nullable=False)
    invitee_id = Column(Integer, ForeignKey("users.id"))  # 如果受邀者已注册
    
    message = Column(Text)
    status = Column(String(20), default="pending")  # pending, accepted, declined, expired
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    expires_at = Column(DateTime(timezone=True))
    responded_at = Column(DateTime(timezone=True))
    
    # 关系
    team = relationship("Team", back_populates="invitations")
    inviter = relationship("User", foreign_keys=[inviter_id])
    invitee = relationship("User", foreign_keys=[invitee_id])